﻿@{
    Layout = null;
    ViewBag.Title = "办公用品领用管理";
    bool isAdmin = ViewBag.IsAdmin ?? false;
    int currentUserId = ViewBag.CurrentUserID ?? 0;
    string currentUserName = ViewBag.CurrentUserName ?? "未知用户";
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>@ViewBag.Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/layui@2.8.18/dist/css/layui.min.css">
    <style>
        .layui-table-view {
            margin: 0;
        }

        .action-buttons {
            margin-bottom: 10px;
        }

        .search-form {
            background: #f8f8f8;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 15px;
        }

        .user-role-info {
            background: #e8f4ff;
            padding: 8px 15px;
            border-radius: 4px;
            margin-bottom: 15px;
            border-left: 4px solid #1890ff;
        }

        .modal-form {
            display: none;
            padding: 20px;
        }

        .table-header {
            background: #f2f2f2;
            padding: 10px 15px;
            border-radius: 4px;
            margin-bottom: 15px;
            border-left: 4px solid #1E9FFF;
        }

        .warning-text {
            color: #ff5722;
            font-weight: bold;
        }

        .normal-text {
            color: #009688;
        }
    </style>
</head>
<body>
    <div class="layui-fluid">
        <div class="layui-row">
            <div class="layui-col-md12">
                <!-- 用户角色与信息区 -->
                <div class="user-role-info">
                    <i class="layui-icon layui-icon-user"></i>
                    当前用户：<span class="layui-badge layui-bg-blue">@currentUserName</span>
                    &nbsp;&nbsp;
                    用户权限：
                    @if (isAdmin)
                    {
                        <span class="layui-badge layui-bg-red">管理员（可审批）</span>
                    }
                    else
                    {
                        <span class="layui-badge layui-bg-green">普通员工（可申请）</span>
                    }
                </div>

                <!-- 搜索筛选区 -->
                <div class="search-form">
                    <form class="layui-form" id="searchForm" lay-filter="searchForm">
                        <div class="layui-form-item">
                            <div class="layui-inline">
                                <label class="layui-form-label">资产名称</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="assetName" autocomplete="off" class="layui-input" placeholder="请输入资产名称">
                                </div>
                            </div>

                            @if (isAdmin)
                            {
                                <div class="layui-inline">
                                    <label class="layui-form-label">申请人</label>
                                    <div class="layui-input-inline">
                                        <input type="text" name="empolyName" autocomplete="off" class="layui-input" placeholder="请输入申请人姓名">
                                    </div>
                                </div>
                            }

                            <div class="layui-inline">
                                <label class="layui-form-label">申请状态</label>
                                <div class="layui-input-inline">
                                    <select name="officeApplyState">
                                        <option value="">全部状态</option>
                                        <option value="0">申请中</option>
                                        <option value="1">已同意</option>
                                        <option value="2">已拒绝</option>
                                    </select>
                                </div>
                            </div>

                            <div class="layui-inline">
                                <button type="button" class="layui-btn layui-btn-normal" id="searchBtn">
                                    <i class="layui-icon">&#xe615;</i>搜索
                                </button>
                                <button type="button" class="layui-btn layui-btn-primary" id="resetBtn">重置</button>

                                @if (!isAdmin)
                                {
                                    <button type="button" class="layui-btn layui-btn-warm" id="applyBtn">
                                        <i class="layui-icon">&#xe654;</i>申请领用
                                    </button>
                                }
                            </div>
                        </div>
                    </form>
                </div>

                <!-- 表格标题 -->
                <div class="table-header">
                    <i class="layui-icon layui-icon-form"></i>
                    <span>办公用品领用记录</span>
                    <span class="layui-badge layui-bg-orange" id="totalCount">0</span>
                </div>

                <!-- 核心表格区 -->
                <table class="layui-hide" id="officeSupplyTable" lay-filter="officeSupplyTable"></table>
            </div>
        </div>
    </div>

    <!-- 申请领用弹窗 -->
    <div id="applyModal" class="modal-form">
        <form class="layui-form" id="applyForm" lay-filter="applyForm">
            <div class="layui-form-item">
                <label class="layui-form-label"><span class="warning-text">*</span>选择资产</label>
                <div class="layui-input-block">
                    <select name="assetId" lay-verify="required" lay-search>
                        <option value="">请选择资产（可搜索）</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label"><span class="warning-text">*</span>申请数量</label>
                <div class="layui-input-block">
                    <input type="number" name="applyNum" lay-verify="required|number|min:1" placeholder="请输入申请数量（至少1）" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">申请用途</label>
                <div class="layui-input-block">
                    <textarea name="applyRemark" placeholder="请输入申请用途或备注信息（可选）" class="layui-textarea" rows="3"></textarea>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit lay-filter="applySubmit">提交申请</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
    </div>

    <!-- 审批弹窗 -->
    <div id="approveModal" class="modal-form">
        <form class="layui-form" id="approveForm" lay-filter="approveForm">
            <input type="hidden" name="recordId" id="approveRecordId">
            <input type="hidden" name="applyNum" id="approveApplyNum">
            <div class="layui-form-item">
                <label class="layui-form-label"><span class="warning-text">*</span>审批结果</label>
                <div class="layui-input-block">
                    <select name="isAgree" id="isAgree" lay-verify="required">
                        <option value="">请选择审批结果</option>
                        <option value="true">同意</option>
                        <option value="false">不同意</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item" id="receiveNumContainer" style="display: none;">
                <label class="layui-form-label"><span class="warning-text">*</span>领取数量</label>
                <div class="layui-input-block">
                    <input type="number" name="receiveNum" id="receiveNum" lay-verify="required|number|min:1" placeholder="请输入实际领取数量" class="layui-input">
                    <p class="layui-form-mid layui-word-aux" id="receiveNumTip">（最多不能超过申请数量）</p>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">审批意见</label>
                <div class="layui-input-block">
                    <textarea name="approveRemark" placeholder="请输入审批意见或说明（可选）" class="layui-textarea" rows="3"></textarea>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit lay-filter="approveSubmit">确认审批</button>
                    <button type="button" class="layui-btn layui-btn-primary" id="cancelApproveBtn">取消</button>
                </div>
            </div>
        </form>
    </div>

    <!-- 详情弹窗 -->
    <div id="detailModal" class="modal-form" style="display: none;">
        <div class="layui-card">
            <div class="layui-card-header">申请详情</div>
            <div class="layui-card-body">
                <div class="layui-form-item">
                    <label class="layui-form-label">资产名称：</label>
                    <div class="layui-input-block">
                        <span id="detailAssetName"></span>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">申请人：</label>
                    <div class="layui-input-block">
                        <span id="detailApplyUser"></span>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">申请数量：</label>
                    <div class="layui-input-block">
                        <span id="detailApplyNum"></span>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">领取数量：</label>
                    <div class="layui-input-block">
                        <span id="detailReceiveNum"></span>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">申请状态：</label>
                    <div class="layui-input-block">
                        <span id="detailApplyState"></span>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">申请日期：</label>
                    <div class="layui-input-block">
                        <span id="detailApplyDate"></span>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">领取日期：</label>
                    <div class="layui-input-block">
                        <span id="detailReceiveDate"></span>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">申请备注：</label>
                    <div class="layui-input-block">
                        <span id="detailRemark"></span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 操作列模板 -->
    <script type="text/html" id="barDemo">
        {{# if(d.OfficeApplyState == 0 && @isAdmin.ToString().ToLower()){ }}
        <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="agree">同意</a>
        <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="disagree">不同意</a>
        {{# } else { }}
        <a class="layui-btn layui-btn-xs layui-btn-primary" lay-event="detail">详情</a>
        {{# } }}
    </script>

    <!-- 状态列模板 -->
    <script type="text/html" id="stateTpl">
        {{#  if(d.OfficeApplyState == 0){ }}
        <span class="layui-badge layui-bg-orange">申请中</span>
        {{#  } else if(d.OfficeApplyState == 1){ }}
        <span class="layui-badge layui-bg-green">已同意</span>
        {{#  } else if(d.OfficeApplyState == 2){ }}
        <span class="layui-badge layui-bg-red">已拒绝</span>
        {{#  } else { }}
        <span class="layui-badge layui-bg-gray">未知</span>
        {{#  } }}
    </script>

    <!-- 日期列模板 - 修正版本 -->
    <script type="text/html" id="dateTpl">
        {{#
            if(d.OfficeApplyDate){
                var date = new Date(d.OfficeApplyDate);
                if(isNaN(date.getTime())) {
                    date = new Date(parseInt(d.OfficeApplyDate.replace(/\D/g, '')));
                }
                var year = date.getFullYear();
                var month = (date.getMonth() + 1).toString().padStart(2, '0');
                var day = date.getDate().toString().padStart(2, '0');
                var hours = date.getHours().toString().padStart(2, '0');
                var minutes = date.getMinutes().toString().padStart(2, '0');
                return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes;
            } else {
        }}
        -
        {{#  } }}
    </script>

    <!-- 领取日期模板 - 修正版本 -->
    <script type="text/html" id="receiveDateTpl">
        {{#
            if(d.OfficeReceiveDate){
                var date = new Date(d.OfficeReceiveDate);
                if(isNaN(date.getTime())) {
                    date = new Date(parseInt(d.OfficeReceiveDate.replace(/\D/g, '')));
                }
                var year = date.getFullYear();
                var month = (date.getMonth() + 1).toString().padStart(2, '0');
                var day = date.getDate().toString().padStart(2, '0');
                var hours = date.getHours().toString().padStart(2, '0');
                var minutes = date.getMinutes().toString().padStart(2, '0');
                return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes;
            } else {
        }}
        -
        {{#  } }}
    </script>

    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/layui@2.8.18/dist/layui.min.js"></script>
    <script>
        layui.use(['table', 'form', 'layer'], function () {
            var table = layui.table;
            var form = layui.form;
            var layer = layui.layer;
            var $ = layui.$;

            var isAdmin = @isAdmin.ToString().ToLower();

            // 日期格式化函数 - 用于详情弹窗
            function formatDate(dateStr) {
                if (!dateStr) return '-';
                try {
                    var date = new Date(dateStr);
                    if (isNaN(date.getTime())) {
                        // 如果是时间戳格式
                        date = new Date(parseInt(dateStr.replace(/\D/g, '')));
                    }
                    return date.getFullYear() + '-' +
                           (date.getMonth() + 1).toString().padStart(2, '0') + '-' +
                           date.getDate().toString().padStart(2, '0') + ' ' +
                           date.getHours().toString().padStart(2, '0') + ':' +
                           date.getMinutes().toString().padStart(2, '0');
                } catch (e) {
                    return dateStr;
                }
            }

            // 初始化表格
            var tableIns = table.render({
                elem: '#officeSupplyTable',
                url: '/OfficeSupplies/GetOfficeSuppliesList',
                method: 'post',
                page: true,
                limit: 10,
                limits: [10, 20, 50],
                loading: true,
                text: {
                    none: '暂无相关数据'
                },
                cols: [[
                    { type: 'numbers', title: '序号', width: 80, fixed: 'left' },
                    { field: 'AssetName', title: '资产名称', width: 180, sort: true },
                    { field: 'ApplyUserName', title: '申请人', width: 120 },
                    { field: 'OfficeApplyNum', title: '申请数量', width: 100, sort: true },
                    { field: 'OfficeReceiveNum', title: '领取数量', width: 100, sort: true },
                    {
                        field: 'OfficeApplyDate',
                        title: '申请日期',
                        width: 160,
                        templet: '#dateTpl',
                        sort: true
                    },
                    {
                        field: 'OfficeReceiveDate',
                        title: '领取日期',
                        width: 160,
                        templet: '#receiveDateTpl',
                        sort: true
                    },
                    {
                        field: 'OfficeApplyState',
                        title: '申请状态',
                        width: 100,
                        templet: '#stateTpl',
                        align: 'center'
                    },
                    {
                        field: 'OfficeRemark',
                        title: '申请备注',
                        minWidth: 200,
                        templet: function(d) {
                            return d.OfficeRemark || '无';
                        }
                    },
                    {
                        fixed: 'right',
                        title: '操作',
                        width: isAdmin ? 180 : 80,
                        align: 'center',
                        toolbar: '#barDemo'
                    }
                ]],
                parseData: function(res) {
                    console.log('表格数据响应:', res);
                    if (res.code === 0) {
                        $('#totalCount').text(res.count || 0);
                    } else {
                        layer.msg(res.msg || '加载数据失败', { icon: 2 });
                    }
                    return {
                        "code": res.code || 0,
                        "msg": res.msg || "",
                        "count": res.count || 0,
                        "data": res.data || []
                    };
                },
                done: function(res, curr, count) {
                    $('#totalCount').text(count || 0);
                }
            });

            // 监听工具条事件
            table.on('tool(officeSupplyTable)', function (obj) {
                var data = obj.data;
                console.log('工具条事件:', obj.event, data);

                if (obj.event === 'agree') {
                    openApproveModal(data.id, data.OfficeApplyNum, true);
                } else if (obj.event === 'disagree') {
                    openApproveModal(data.id, data.OfficeApplyNum, false);
                } else if (obj.event === 'detail') {
                    showDetailModal(data);
                }
            });

            // 搜索功能
            $('#searchBtn').on('click', function () {
                var formData = form.val('searchForm');
                console.log('搜索条件:', formData);
                tableIns.reload({
                    where: formData,
                    page: { curr: 1 }
                });
            });

            // 重置功能
            $('#resetBtn').on('click', function () {
                form.val('searchForm', {
                    assetName: '',
                    empolyName: '',
                    officeApplyState: ''
                });
                form.render();
                tableIns.reload({
                    where: {},
                    page: { curr: 1 }
                });
            });

            // 申请领用弹窗
            $('#applyBtn').on('click', function () {
                loadAvailableAssets();
                layer.open({
                    type: 1,
                    title: '申请领用办公用品',
                    area: ['500px', '420px'],
                    content: $('#applyModal'),
                    success: function() {
                        form.val('applyForm', {
                            assetId: '',
                            applyNum: '',
                            applyRemark: ''
                        });
                    }
                });
            });

            // 加载可用资产
            function loadAvailableAssets() {
                layer.load(1);
                $.post('/OfficeSupplies/GetAvailableAssets', function(res) {
                    layer.closeAll('loading');
                    console.log('可用资产响应:', res);
                    if (res.code === 0) {
                        var select = $('select[name="assetId"]');
                        select.empty();
                        select.append('<option value="">请选择资产（可搜索）</option>');
                        $.each(res.data, function(index, asset) {
                            var displayText = asset.AssetName;
                            if (asset.AssetModel) {
                                displayText += ' (' + asset.AssetModel + ')';
                            }
                            select.append('<option value="' + asset.AssetID + '">' + displayText + '</option>');
                        });
                        form.render('select');
                    } else {
                        layer.msg(res.msg || '加载资产失败', { icon: 2 });
                    }
                }).fail(function(xhr, status, error) {
                    layer.closeAll('loading');
                    console.error('加载资产失败:', error);
                    layer.msg('网络错误，请重试', { icon: 2 });
                });
            }

            // 申请表单提交
            form.on('submit(applySubmit)', function(data) {
                var formData = data.field;
                var submitBtn = $(this);

                console.log('提交申请数据:', formData);

                submitBtn.prop('disabled', true).addClass('layui-btn-disabled');

                $.post('/OfficeSupplies/SubmitApply', {
                    assetId: formData.assetId,
                    applyNum: formData.applyNum,
                    applyRemark: formData.applyRemark
                }, function(res) {
                    console.log('申请提交响应:', res);
                    submitBtn.prop('disabled', false).removeClass('layui-btn-disabled');

                    if (res.code === 0) {
                        layer.msg(res.msg, {
                            icon: 1,
                            time: 2000
                        }, function() {
                            layer.closeAll();
                            tableIns.reload();
                            form.val('applyForm', {
                                assetId: '',
                                applyNum: '',
                                applyRemark: ''
                            });
                        });
                    } else {
                        layer.msg(res.msg || '申请失败', { icon: 2 });
                    }
                }).fail(function(xhr, status, error) {
                    console.error('申请提交失败:', error);
                    submitBtn.prop('disabled', false).removeClass('layui-btn-disabled');
                    layer.msg('网络错误，请重试', { icon: 2 });
                });
                return false;
            });

            // 打开审批弹窗
            function openApproveModal(id, applyNum, isAgree) {
                $('#approveRecordId').val(id);
                $('#approveApplyNum').val(applyNum);
                $('#isAgree').val(isAgree.toString());

                if (isAgree) {
                    $('#receiveNumContainer').show();
                    $('#receiveNum').attr({
                        'min': 1,
                        'max': applyNum
                    });
                    $('#receiveNumTip').text('（申请数量：' + applyNum + '，领取数量不能超过申请数量）');
                    $('#receiveNum').val(applyNum);
                } else {
                    $('#receiveNumContainer').hide();
                    $('#receiveNum').val('');
                }

                form.render();

                layer.open({
                    type: 1,
                    title: '审批申请',
                    area: ['500px', '420px'],
                    content: $('#approveModal'),
                    success: function() {
                        form.val('approveForm', {
                            approveRemark: ''
                        });
                    }
                });
            }

            // 审批结果选择事件
            form.on('select(isAgree)', function(data) {
                var isAgree = data.value === 'true';
                var applyNum = $('#approveApplyNum').val();

                if (isAgree) {
                    $('#receiveNumContainer').show();
                    $('#receiveNum').attr({
                        'min': 1,
                        'max': applyNum
                    });
                    $('#receiveNumTip').text('（申请数量：' + applyNum + '，领取数量不能超过申请数量）');
                    $('#receiveNum').val(applyNum);
                } else {
                    $('#receiveNumContainer').hide();
                    $('#receiveNum').val('');
                }
                form.render();
            });

            // 审批表单提交
            form.on('submit(approveSubmit)', function(data) {
                var formData = data.field;
                var receiveNum = formData.isAgree === 'true' ? parseInt(formData.receiveNum) : null;
                var submitBtn = $(this);

                console.log('审批提交数据:', formData);

                submitBtn.prop('disabled', true).addClass('layui-btn-disabled');

                $.post('/OfficeSupplies/ApproveApply', {
                    id: formData.recordId,
                    isAgree: formData.isAgree === 'true',
                    receiveNum: receiveNum,
                    approveRemark: formData.approveRemark
                }, function(res) {
                    console.log('审批响应:', res);
                    submitBtn.prop('disabled', false).removeClass('layui-btn-disabled');

                    if (res.code === 0) {
                        layer.msg(res.msg, {
                            icon: 1,
                            time: 2000
                        }, function() {
                            layer.closeAll();
                            tableIns.reload();
                        });
                    } else {
                        layer.msg(res.msg || '审批失败', { icon: 2 });
                    }
                }).fail(function(xhr, status, error) {
                    console.error('审批提交失败:', error);
                    submitBtn.prop('disabled', false).removeClass('layui-btn-disabled');
                    layer.msg('网络错误，请重试', { icon: 2 });
                });
                return false;
            });

            // 显示详情弹窗
            function showDetailModal(data) {
                $('#detailAssetName').text(data.AssetName || '-');
                $('#detailApplyUser').text(data.ApplyUserName || '-');
                $('#detailApplyNum').text(data.OfficeApplyNum || '0');
                $('#detailReceiveNum').text(data.OfficeReceiveNum || '0');
                $('#detailApplyDate').text(formatDate(data.OfficeApplyDate) || '-');
                $('#detailReceiveDate').text(formatDate(data.OfficeReceiveDate) || '-');
                $('#detailRemark').text(data.OfficeRemark || '无');

                // 设置状态显示
                var stateText = '';
                var stateClass = '';
                if (data.OfficeApplyState == 0) {
                    stateText = '申请中';
                    stateClass = 'layui-bg-orange';
                } else if (data.OfficeApplyState == 1) {
                    stateText = '已同意';
                    stateClass = 'layui-bg-green';
                } else if (data.OfficeApplyState == 2) {
                    stateText = '已拒绝';
                    stateClass = 'layui-bg-red';
                } else {
                    stateText = '未知';
                    stateClass = 'layui-bg-gray';
                }
                $('#detailApplyState').html('<span class="layui-badge ' + stateClass + '">' + stateText + '</span>');

                layer.open({
                    type: 1,
                    title: '申请详情',
                    area: ['500px', '500px'],
                    content: $('#detailModal')
                });
            }

            // 取消审批
            $('#cancelApproveBtn').on('click', function() {
                layer.closeAll();
            });
        });
    </script>
</body>
</html>